package com.only4play.system.infrastructure.third.email;

import com.only4play.extension.executor.Extension;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;


/**
 * @author jialiang 2024/12/10 9:58
 */
@Slf4j
@Service
@Extension(bizId = EmailBizId.QQ_EMAIL_BIZ)
public class EmailSendServiceImpl implements IEmailSendService {

    /**
     * 邮箱正则表达式
     */
    private static final String EMAIL_REGEX =
            "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";


    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    @Autowired
    private QQEmailConfigProperties qqEmailConfigProperties;


    @Override
    public boolean sendEmail(EmailSendModel sendModel) {
        if (sendModel.getMailbox() == null || sendModel.getMailbox().isEmpty()) {
            log.error("收件人邮箱列表为空");
            return false;
        }

        for (String email : sendModel.getMailbox()) {
            validateEmail(email);
            try {
                MimeMessage message = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setSubject(sendModel.getSubject());
                helper.setFrom(new InternetAddress(qqEmailConfigProperties.getUsername(), sendModel.getTitle()));
                helper.setTo(email);
                helper.setSentDate(new Date());
                helper.setText(sendModel.getContent());
                javaMailSender.send(message);
                log.debug("邮件发送成功给: {}", email);
            } catch (MessagingException | UnsupportedEncodingException e) {
                log.error("邮件发送失败给: {}，错误信息: {}", email, e.getMessage());
                return false;
            }
        }

        return true;
    }

    private static void validateEmail(String email) throws IllegalArgumentException {
        if (email == null || !email.matches(EMAIL_REGEX) ||email.isEmpty()) {
            throw new IllegalArgumentException("无效的电子邮件地址: " + email);
        }
    }
}
